<?php

namespace App\Models\Game\Mail;

use App\Models\Game\Model;
use App\Models\Game\User\User;
use App\Models\Game\Common\Dictionary;
use App\Models\Traits\Game\LogsActivity;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Player extends Model
{
    use SoftDeletes, LogsActivity;

    /**
     * 数据表名称
     *
     * @var string
     */
    protected $table = 't_mail_player';

    /**
     * 不可批量赋值的属性
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * 进行类型转换的字段
     *
     * @var array
     */
    protected $casts = [
        'body_param' => 'array',
        'annex' => 'array',
        'deleted' => 'timestamp',
        'created' => 'timestamp',
        'updated' => 'timestamp'
    ];

    /**
     * 获取邮件状态
     *
     * @param int|null $value
     * @return array
     */
    public function getStatusAttribute(?int $value): array
    {
        return decimal_to_binary_bits($value);
    }

    /**
     * 邮件收件人
     *
     * @return BelongsTo
     */
    public function receiver()
    {
        return $this->belongsTo(User::class, 'receiver_id', 'id');
    }

    /**
     * 拥有此邮件的所有字典【标题】
     *
     * @return BelongsToMany
     */
    public function titles(): BelongsToMany
    {
        return $this->belongsToMany(Dictionary::class, PlayerDictionary::tableName(), 'mail_id', 'dict_id')
            ->wherePivot('mail_content_type', PlayerDictionary::TYPE_TITLE)
            ->withTrashed();
    }

    /**
     * 拥有此邮件的所有字典【内容】
     *
     * @return BelongsToMany
     */
    public function bodys(): BelongsToMany
    {
        return $this->belongsToMany(Dictionary::class, PlayerDictionary::tableName(), 'mail_id', 'dict_id')
            ->wherePivot('mail_content_type', PlayerDictionary::TYPE_BODY)
            ->withTrashed();
    }
}
